#include "flag2status.h"

Flag2Status::Flag2Status(QWidget *parent)
    : QWidget{parent}
{}

Flag2Status::Flag2Status(const QJsonObject &statusDetails, QWidget *parent)
    : QWidget{parent}
{

    setupControlLayout(statusDetails);  // 设置控件的布局
}

void Flag2Status::setupControlLayout(const QJsonObject &statusDetails)
{
    QHBoxLayout *mainLayout = new QHBoxLayout(this);
    mainLayout->setContentsMargins(0, 0, 0, 0);
    mainLayout->setSpacing(6);  // 控制两个 rowWidget 之间的间距

    // ========== 左侧 rowWidget ========== //
    QWidget *leftRow = new QWidget(this);
    leftRow->setStyleSheet(R"(
        QWidget {
            background-color: #22314a;
            border-radius: 6px;
            padding: 4px 4px;
        }
    )");
    QHBoxLayout *leftLayout = new QHBoxLayout(leftRow);
    leftLayout->setContentsMargins(8, 4, 8, 4);
    leftLayout->setSpacing(4);

    QLabel *icon1 = new QLabel(leftRow);
    icon1->setPixmap(QIcon(":/img/fa-cog.png").pixmap(20, 20));
    leftLayout->addWidget(icon1);

    QString label1Text = statusDetails.value("label1").toString();
    QString label2Text = statusDetails.value("label2").toString();
    QString lineEdit1Name = statusDetails.value("lineedit1").toString();

    QLabel *label1 = new QLabel(label1Text, leftRow);
    label1->setStyleSheet("color: #94a3b8; font-size: 16px;");
    leftLayout->addWidget(label1);

    leftLayout->addStretch();  // 左侧 label 和 lineEdit 之间插入弹簧

    QLineEdit *lineEdit1 = new QLineEdit(leftRow);
    lineEdit1->setObjectName(lineEdit1Name);
    lineEdit1->setReadOnly(true);
    lineEdit1->setMaximumWidth(100);  // 控制最大宽度
    lineEdit1->setAlignment(Qt::AlignRight);
    lineEdit1->setStyleSheet("color: white; font-weight: bold; font-size: 16px; background: transparent; border: none;");
    leftLayout->addWidget(lineEdit1);
    fieldLineEdits.insert(lineEdit1Name, lineEdit1);

    QLabel *unitLabel1 = new QLabel(label2Text, leftRow);
    unitLabel1->setStyleSheet("color: white; font-size: 16px; font-weight: bold;");
    leftLayout->addWidget(unitLabel1);

    // ========== 右侧 rowWidget ========== //
    QWidget *rightRow = new QWidget(this);
    rightRow->setStyleSheet(R"(
        QWidget {
            background-color: #22314a;
            border-radius: 6px;
            padding: 4px 4px;
        }
    )");
    QHBoxLayout *rightLayout = new QHBoxLayout(rightRow);
    rightLayout->setContentsMargins(8, 4, 8, 4);
    rightLayout->setSpacing(4);

    QLabel *icon2 = new QLabel(rightRow);
    icon2->setPixmap(QIcon(":/img/fa-cog.png").pixmap(20, 20));
    rightLayout->addWidget(icon2);

    QString label3Text = statusDetails.value("label3").toString();
    QString label4Text = statusDetails.value("label4").toString();
    QString lineEdit2Name = statusDetails.value("lineedit2").toString();

    QLabel *label3 = new QLabel(label3Text, rightRow);
    label3->setStyleSheet("color: #94a3b8; font-size: 16px;");
    rightLayout->addWidget(label3);

    rightLayout->addStretch();  // label 与 lineedit 之间插入弹簧

    QLineEdit *lineEdit2 = new QLineEdit(rightRow);
    lineEdit2->setObjectName(lineEdit2Name);
    lineEdit2->setReadOnly(true);
    lineEdit2->setMaximumWidth(100);  // 控制最大宽度
    lineEdit2->setAlignment(Qt::AlignRight);
    lineEdit2->setStyleSheet("color: white; font-weight: bold; font-size: 16px; background: transparent; border: none;");
    rightLayout->addWidget(lineEdit2);
    fieldLineEdits.insert(lineEdit2Name, lineEdit2);

    QLabel *unitLabel2 = new QLabel(label4Text, rightRow);
    unitLabel2->setStyleSheet("color: white; font-size: 16px; font-weight: bold;");
    rightLayout->addWidget(unitLabel2);

    // 添加左右行到主布局
    mainLayout->addWidget(leftRow);
    mainLayout->addWidget(rightRow);

    // 缓存结构
    fg.label1Text = label1Text;
    fg.label3Text = label3Text;
    fg.lineEdit1 = lineEdit1;
    fg.lineEdit2 = lineEdit2;
    fieldGroups.insert(label1Text, fg);
}


void Flag2Status::updateFieldValue(const QString &fieldName, int lineEditIndex, const QString &newValue)
{
    if (!fieldGroups.contains(fieldName)) {
        qWarning() << "Field group not found:" << fieldName;
        return;
    }

    FieldGroup &fg = fieldGroups[fieldName];
    if (lineEditIndex == 1 && fg.lineEdit1) {
        fg.lineEdit1->setText(newValue);
    } else if (lineEditIndex == 2 && fg.lineEdit2) {
        fg.lineEdit2->setText(newValue);
    } else {
        qWarning() << "Invalid lineEdit index or null pointer";
    }
}

void Flag2Status::updateFieldValue(const QString &fieldName, const QString &newValue)
{
    if (fieldLineEdits.contains(fieldName)) {
        fieldLineEdits[fieldName]->setText(newValue);  // 更新 QLineEdit 的值
    } else {
        //qWarning() << "Field name not found: " << fieldName;
    }
}

void Flag2Status::attachToNode(QSharedPointer<DeviceNode> node)
{
    if (m_node) {
        disconnect(m_node.data(), &DeviceNode::cmdReceived,
                   this, &Flag2Status::onDataReceived);
        disconnect(m_node.data(), &DeviceNode::eventReceived,
                   this, &Flag2Status::onEventReceived);
    }
    m_node = node;
    if (m_node) {
        connect(m_node.data(), &DeviceNode::cmdReceived,
                this, &Flag2Status::onDataReceived);
        connect(m_node.data(), &DeviceNode::eventReceived,
                this, &Flag2Status::onEventReceived);
    }
}

void Flag2Status::onEventReceived(const QString& content)
{
    //m_eventLabel->setText("Event: " + content);
    //qDebug()<<"Flag2Status Received Event "<<content<<Qt::endl;
    subEventCallBack(content);
}

// void Flag2Status::onDataReceived(const QString &content)
// {
//     if(flagLimit1)
//     {
//         dataAnayle(content);
//         flagLimit1 = false;
//     }
//     else
//         flagLimit1 = true;
// }


void Flag2Status::onDataReceived(const QString& content)
{
    //qDebug() << "Flag2Status Node Received Statu " << content << Qt::endl;

    // 解析JSON字符串
    QJsonDocument doc = QJsonDocument::fromJson(content.toUtf8());

    // 判断是否成功解析
    if (doc.isObject()) {
        QJsonObject obj = doc.object();

        // 遍历JSON对象的所有键值对
        QJsonObject::const_iterator iter = obj.constBegin();
        QString key;
        QJsonValue value;
        QString valueF;
        while (iter != obj.constEnd()) {
            // 打印每个键和值
            key = iter.key();
            value = iter.value();
            valueF = " ";
            // 根据值的类型
            if(value.isArray())
            {
                QJsonArray jsonArray = value.toArray();
                int i=1;
                QString nameX;
                for (const auto &value : jsonArray) {
                    //nameArray.push_back(value.toDouble());
                    valueF = QString::number(value.toDouble());
                    nameX = key+QString::number(i);
                    // qDebug() <<"now status key = "<< nameX <<Qt::endl;
                    // qDebug() <<"now status value = "<< valueF <<Qt::endl;
                    QMetaObject::invokeMethod(this, [this, nameX, valueF]() {
                        updateFieldValue(nameX, valueF);
                    }, Qt::QueuedConnection);
                    i++;
                }
                ++iter;
                continue;
            }

            if (value.isDouble()) {
                //qDebug() << key << ": " << value.toDouble();
                valueF = QString::number(value.toDouble());
            } else if (value.isBool()) {

                valueF = value.toBool() ? "TRUE" : "FALSE";
            } else if (value.isString()) {
                //qDebug() << key << ": " << value.toString();
                valueF = value.toString();
            } else {
                qDebug() << key << ": unknown type";
            }
            // qDebug() <<"now status key = "<< key <<Qt::endl;
            // qDebug() <<"now status value = "<< valueF <<Qt::endl;
            QMetaObject::invokeMethod(this, [this, key, valueF]() {
                updateFieldValue(key, valueF);
            }, Qt::QueuedConnection);

            // 前进到下一个键值对
            ++iter;
        }
    } else {
        qDebug() << "Failed to parse JSON." << Qt::endl;
    }
}

void Flag2Status::subEventCallBack(const QString& content)
{

}
// 返回 label1 的文本
QString Flag2Status::getLabel1() const
{
    return fg.label1Text;  // 返回 label1 的文本
}

// 返回 label3 的文本
QString Flag2Status::getLabel3() const
{
    return fg.label3Text;  // 返回 label3 的文本
}

QLineEdit* Flag2Status::getLineEdit1() const
{
    return fg.lineEdit1;  // 返回 lineEdit1
}

QLineEdit* Flag2Status::getLineEdit2() const
{
    return fg.lineEdit2;  // 返回 lineEdit2
}



